package com.zhuangjie.mvc.validator.handler;

import com.zhuangjie.mvc.validator.annotate.enum_valid.EnumValid;
import com.zhuangjie.mvc.validator.annotate.enum_valid.VerifiableEnum;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Objects;

public class EnumValidValidator implements ConstraintValidator<EnumValid, Number> {

    private EnumValid enumValid;

    @Override
    public void initialize(EnumValid enumValid) {
        this.enumValid = enumValid;
    }

    @Override
    public boolean isValid(Number value, ConstraintValidatorContext context) {
        if (value == null) return enumValid.allowNull();
        Class<? extends VerifiableEnum> clazz = enumValid.value();
        Field[] fields = clazz.getDeclaredFields(); // 获取到所有的字段，包括private和protected
        for (Field field : fields) {
            if (Modifier.isStatic(field.getModifiers())) { // 判断字段是否为静态
                field.setAccessible(true); // 如果是私有静态属性，需要先调用setAccessible设置可访问
                try {
                    Object o = field.get(null);
                    if (o instanceof VerifiableEnum) {
                        if (Objects.equals(((VerifiableEnum)o).getValue(),value.byteValue())) {
                            return true;
                        }
                    }
                } catch (IllegalArgumentException | IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }

        return false;
    }
}